package org.bigk.invoices.services;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.DecimalFormat;
import java.text.NumberFormat;

import org.apache.commons.lang.StringUtils;
import org.bigk.invoices.model.Invoice;

/**
 * Y5DN - Year and then 5 digits of Number. What I mean is human readable
 * format: Year/5-digit-Number. When Number is shorter than 5 digits, it will be
 * preceded by 'zero' signs.
 * 
 * @author lukasz.kalek
 * 
 */
public class HRInvoiceNumberServiceY5DNImpl implements HRInvoiceNumberService {
	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory
			.getLog(HRInvoiceNumberServiceY5DNImpl.class);

	public static final NumberFormat LONG_5_LEADING_ZEROS_DF = new DecimalFormat("00000");
	
	@Override
	public boolean updateHRInvoiceNumber(Invoice invoice) {
		if (logger.isDebugEnabled()) {
			logger.debug("updateHRInvoiceNumber(Invoice invoice=" + invoice
					+ ") - start");
		}
		
		if (StringUtils.isEmpty(invoice.getYear())) {
			if (logger.isDebugEnabled()) {
				logger.debug("updateHRInvoiceNumber(Invoice) - end - return value=" + false);
			}
			return false;
		}
		
		if (invoice.getNumber() == null) {
			if (logger.isDebugEnabled()) {
				logger.debug("updateHRInvoiceNumber(Invoice) - end - return value=" + false);
			}
			return false;
		}
		
		String hrNo = invoice.getYear() + "/"
				+ LONG_5_LEADING_ZEROS_DF.format(invoice.getNumber());
		invoice.setHrInvoiceNumber(hrNo);
		
		if (logger.isDebugEnabled()) {
			logger.debug("updateHRInvoiceNumber(Invoice) - end - return value=" + true);
		}
		return true;
	}
	
}
